package cn.zyjw.service.impl;

import cn.zyjw.domain.WorkIssue;
import cn.zyjw.dto.UserDto;
import cn.zyjw.feign.UserServiceFeign;
import cn.zyjw.mapper.WorkIssueMapper;
import cn.zyjw.service.WorkIssueService;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WorkIssueServiceImpl extends ServiceImpl<WorkIssueMapper, WorkIssue> implements WorkIssueService {

    @Autowired
    private UserServiceFeign userServiceFeign;

    /**
     * 列表分页查询
     *
     * @param page
     * @return
     */
    @Override
    public Page<WorkIssue> findByPage(Page<WorkIssue> page) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<WorkIssue> workIssuePage = page(page);

        List<WorkIssue> records = workIssuePage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return workIssuePage;
        }
        List<Long> userIds = records.stream().map(WorkIssue::getUserId).collect(Collectors.toList());
        List<UserDto> basicUsers = userServiceFeign.getBasicUsers(userIds);
        if (CollectionUtils.isEmpty(basicUsers)) {
            return workIssuePage;
        }
        Map<Long, UserDto> dtoMap = basicUsers.stream().collect(Collectors.toMap(UserDto::getId, user -> user));

        records.forEach(workIssue -> {
            UserDto userDto = dtoMap.get(workIssue.getUserId());
            workIssue.setUsername(userDto==null?"测试用户":userDto.getUsername());
            workIssue.setRealName(userDto==null?"测试用户":userDto.getRealName());

        });
        return workIssuePage;
    }
}
